package com.smartian.app.adapter;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.lang.ref.SoftReference;

public abstract class AbstractBaseFragment extends Fragment {

    private SoftReference<View> mFragmentViewCache = null; //实现viewcache
    private boolean isFinishedInflated = false;
    private Bundle mNoneStateArguments;
    private int position = -1;

    @Nullable
    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = null;
        if (!isEmptyFragmentCache()) {
            root = mFragmentViewCache.get();
        }
        if (root == null) {
            root = onDoCreateView(inflater, container, savedInstanceState);
            mFragmentViewCache = new SoftReference<View>(root);
        }
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            isFinishedInflated = true;
            onDoViewCreated(view, savedInstanceState);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected abstract View onDoCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    protected abstract void onDoViewCreated(View view, Bundle savedInstanceState);

    public abstract void onShowFragment();

    public abstract void onHideFragment();

    private boolean isEmptyFragmentCache() {
        return mFragmentViewCache == null || mFragmentViewCache.get() == null;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            onShowFragment();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isFinishedInflated) return;
        if (getUserVisibleHint()) {
            onShowFragment();
        } else if (isResumed()) {
            onHideFragment();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (getUserVisibleHint()) {
            onHideFragment();
        }
    }
    public void setNoneStateArguments(Bundle bundle) {  //解决已初始化状态的参数刷新问题
        this.mNoneStateArguments = bundle;
    }
    public Bundle getNoneStateArguments() {
        return this.mNoneStateArguments != null ? this.mNoneStateArguments : new Bundle();
    }
    public void setPosition(int position) {
        this.position = position;
    }

    public int getPosition() {
        return this.position;
    }
    /**
     * 刷新Fragment，防止WebView复用，建议检查参数
     */
    public abstract void refreshFragment();

}